<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\annotations\parsers;

#use \ReflectionException;
#use tehframework\annotations\AnnotationDefinition;

class AnnotationParserImpl extends AnnotationParser
{
	/**
	 * @var ArrayParser
	 */
	private $arrayParser;
	
	/**
	 * @param  ArrayParser $ArrayParser
	 */
	public function __construct(ArrayParser $arrayParser)
	{
		$this->arrayParser = $arrayParser;
	}
	
	/**
	 * @param  string $annotationValue
	 * @return AnnotationDefinition
	 * @throws ParserException
	 */
	public function parseAnnotation($annotation)
	{
		$match   = array();
		$matches = preg_match(
			'#^\@(?P<name>.*?)(?:\<(?P<type>.*?)\>)?(?:\[(?P<parameter>.*?)\])?' . 
			'(?:\((?P<data>.*?)\))?$#s',
			trim($annotation),
			$match
		);
		
		if ($matches === 0)
		{
			throw new ParserException(
				'Invalid string representation of an annotation specified.'
			);
		}
		
		$name = str_replace('.', T_NS_SEPARATOR,
			(strlen($match['name']) !== 10) &&
			(substr($match['name'], -10) === 'Annotation')
				? substr($match['name'], 0, -10)
				: $match['name']);
		
		$type = isset($match['type']) && !empty($match['type'])
			? $match['type'] : null;
		
		$parameter = isset($match['parameter']) && !empty($match['parameter'])
			? $match['parameter'] : null;
		
		$data = isset($match['data']) ? trim($match['data']) : null;
		
		if (!empty($data))
		{
			$data = $this->arrayParser->parseArray('{' . $data . '}');
		}
		else
		{
			$data = array();
		}
		
		$arguments  = array();
		$properties = array();
		
		foreach ($data as $k => $v)
		{
			if (is_integer($k))
			{
				$arguments[] = $v;
			}
			else
			{
				$properties[$k] = $v;
			}
		}
		
		return new AnnotationDefinition(
			$name, $type, $parameter, $arguments, $properties
		);
	}
}